package com.xdap.wecom.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.definesys.mpaas.common.http.Response;
import com.xdap.api.moudle.user.vo.LoginUserVo;
import com.xdap.app.utils.Base64Util;
import com.xdap.common.config.LocalValue;
import com.xdap.common.dao.ComProcessInstanceDao;
import com.xdap.common.dao.ComUserDao;
import com.xdap.common.pojo.dto.webhook.UserDTO;
import com.xdap.common.pojo.dto.webhook.WebhookProcessDto;
import com.xdap.common.pojo.dto.webhook.XdapProcInstanceDto;
import com.xdap.common.pojo.po.ComUserPo;
import com.xdap.common.util.ApaasTokenUtil;
import com.xdap.common.util.ComPluginPropertiesUtil;
import com.xdap.common.util.ComStrUtil;
import com.xdap.processapi.pojo.entity.XdapProcInstance;
import com.xdap.runtime.service.RuntimeAppContextService;
import com.xdap.runtime.service.RuntimeUserService;
import com.xdap.wecom.client.WeComClient;
import com.xdap.wecom.client.WeComResponse;
import com.xdap.wecom.pojo.dto.WeComMsgDto;
import com.xdap.wecom.pojo.dto.WxTextcardDto;
import com.xdap.wecom.service.WecomWebhookService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName techking-plan-plugin
 * @Description
 * @Date 2023/11/16 10:27
 * @Author shangsheng.li
 **/
@Slf4j
@Service
@LocalValue
@RequiredArgsConstructor
public class WecomWebhookServiceImpl implements WecomWebhookService {

    @Resource
    private RuntimeUserService runtimeUserService;

    @Resource
    private RuntimeAppContextService runtimeAppContextService;

    @Resource
    private ComUserDao comUserDao;

    @Resource
    private ApaasTokenUtil apaasTokenUtil;

    @Value("${xdap.share.frontSingleAppHost}")
    private String appHost;

    @LocalValue("${techking.wecom.agentId}")
    private String agentId;

    @Resource
    private WeComClient weComClient;

    @Resource
    private ComProcessInstanceDao crmProcessInstanceDao;

    @Override
    public Response wxApproveMsgSend(WebhookProcessDto webhookProcessPojo) {
        XdapProcInstanceDto xdapProcInstance = webhookProcessPojo.getXdapProcInstance();
        List<UserDTO> approverDTO = xdapProcInstance.getApproverDTO();
        approverDTO.forEach(userDTO -> {
            log.info("审批人：{}", JSONObject.toJSONString(userDTO));
            String approveUserId = userDTO.getUserId();
            ComUserPo userById = comUserDao.getUserById(approveUserId);
            String userNumber = userById.getUserNumber();
            try {
                String formUrl = this.getFormUrl(xdapProcInstance, ComStrUtil.getData(approveUserId));
                String msgTitle = ComPluginPropertiesUtil.getProperty("techking.wecom.msg.title");
                String description = ComPluginPropertiesUtil.getProperty("techking.wecom.msg.description");
                WxTextcardDto wxTextcardDto = WxTextcardDto.builder()
                        .title(msgTitle)
                        .description(description)
                        .url(formUrl)
                        .build();
                WeComMsgDto weComMsgDto = WeComMsgDto.builder()
                        .touser(userNumber)
                        .msgtype("textcard")
                        .agentid(Long.parseLong(agentId))
                        .textcard(wxTextcardDto)
                        .enable_id_trans(0)
                        .enable_duplicate_check(0)
                        .build();
                log.info("请求企业微信文本卡片消息入参：{}", JSONArray.toJSONString(weComMsgDto));
                WeComResponse weComResponse = weComClient.sendWxTextMsg(weComMsgDto);
                log.info("企业微信文本卡片消息发送返回：{}", JSONArray.toJSONString(weComResponse));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        });
        return Response.ok();
    }

    @Override
    public Response rePushWxMsg() {
        List<XdapProcInstance> xdapProcInstances = crmProcessInstanceDao.queryApprovingAll();
        log.info("超时数据：{}条", xdapProcInstances.size());
        xdapProcInstances.stream().forEach(xdapProcInstance -> {
            XdapProcInstanceDto xdapProcInstanceDto = new XdapProcInstanceDto();
            xdapProcInstanceDto.setFormId(xdapProcInstance.getFormId());
            xdapProcInstanceDto.setAppId(xdapProcInstance.getAppId());
            xdapProcInstanceDto.setDocumentId(xdapProcInstance.getDocumentId());
            log.info("数据：{}", JSONArray.toJSONString(xdapProcInstance));
            String approveUserId = ComStrUtil.getData(xdapProcInstance.getApprover());
            log.info("审批人：{}", JSONObject.toJSONString(approveUserId));
            ComUserPo userById = comUserDao.getUserById(approveUserId);
            String userNumber = userById.getUserNumber();
            try {
                String formUrl = this.getFormUrl(xdapProcInstanceDto, ComStrUtil.getData(approveUserId));
                String msgTitle = ComPluginPropertiesUtil.getProperty("techking.wecom.msg.title");
                String description = ComPluginPropertiesUtil.getProperty("techking.wecom.msg.description");
                WxTextcardDto wxTextcardDto = WxTextcardDto.builder()
                        .title(msgTitle)
                        .description(description)
                        .url(formUrl)
                        .build();
                WeComMsgDto weComMsgDto = WeComMsgDto.builder()
                        .touser(userNumber)
                        .msgtype("textcard")
                        .agentid(Long.parseLong(agentId))
                        .textcard(wxTextcardDto)
                        .enable_id_trans(0)
                        .enable_duplicate_check(0)
                        .build();
                log.info("请求企业微信文本卡片消息入参：{}", JSONArray.toJSONString(weComMsgDto));
                WeComResponse weComResponse = weComClient.sendWxTextMsg(weComMsgDto);
                log.info("企业微信文本卡片消息发送返回：{}", JSONArray.toJSONString(weComResponse));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        });
        return Response.ok();
    }

    private LoginUserVo getUserById(String userId) {
        LoginUserVo loginUserVo = runtimeUserService.queryLoginUserVo(userId,
                runtimeAppContextService.getCurrentTenantId(), runtimeAppContextService.getCurrentAppId());
        return loginUserVo;
    }

    public String getFormUrl(XdapProcInstanceDto xdapProcInstance, String userId) throws UnsupportedEncodingException {
        String formId = xdapProcInstance.getFormId();
        String appId = xdapProcInstance.getAppId();
        Map<String, Object> state = new HashMap<>();
        Map<String, Object> m1 = new HashMap<>();
        m1.put("formId", formId);
        m1.put("appId", appId);
        m1.put("documentId", xdapProcInstance.getDocumentId());
        m1.put("readOnly", "isApprove");
        m1.put("module", "approvePage");
        log.info("生成token:{}", userId);
        String token = apaasTokenUtil.createToken(userId);
        log.info("token:{}", token);
        state.put("m1", m1);
        log.info("m1:{}", m1);
        byte[] bytes = JSONObject.toJSONString(state).getBytes(StandardCharsets.UTF_8);
        log.info("state:" + JSONObject.toJSONString(state));
        String stateBase64 = Base64Util.encode(bytes);
        log.info("stateBase64:" + stateBase64);


        String backUrl = appHost + "callback/apaas/index.html?xdaptoken=" +
                token + "&state=" + stateBase64;
        log.info("跳转地址为：" + backUrl);

        return backUrl;
    }

}
